/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controllers.filters;

import controllers.pipes.Reader2ValidatorPipe;
import controllers.pipes.Validator2PersistencePipe;
import javafx.concurrent.Task;

/**
 *
 * @author Sergio
 */
public final class SyntacticValidatorFilter extends Task {

  private long lines = 0;

  public void setLines(long lines) {
    this.lines = lines;
  }

  public SyntacticValidatorFilter() {
//    super("SyntacticValidator");
    System.out.println("Starting thread: " + this);
  }

  @Override
  protected Object call() throws Exception {
    try {
      Reader2ValidatorPipe theInQueueInstance = Reader2ValidatorPipe.getInstance();
      Validator2PersistencePipe theOutQueueInstance = Validator2PersistencePipe.getInstance();
      while (lines == 0) {
        Thread.sleep(200);//number of lines has not been initialized, wait some time.
      }
      final long limit=lines;
      for (int i = 0; i < limit;) {
        String currentWord = theInQueueInstance.getElement();//read from the pipe.
        if (currentWord == null) {
          System.out.println("There is nothing here VALIDATOR!!");//nothing in the pipe. Wait.
        } else {
          //send to validation
          int validationResult = Validate(currentWord);
          //valitation returns an error code.
          //si es cero., pinte bien
//          Coll
          String[] cases = new String[10];
          cases[0] = " correcta.";
          cases[1] = " incorrecta: Tipo de documento invalido.";
          cases[2] = " incorrecta: Numero de documento invalido.";
          cases[3] = " incorrecta: Nombre en la tarjeta invalido.";
          cases[4] = " incorrecta: Tipo de tarjeta invalido.";
          cases[5] = " incorrecta: Numero de tarjeta invalido.";
          cases[6] = " incorrecta: Franquicia invalida.";
          cases[7] = " incorrecta: Monto de transaccion invalido.";
          cases[8] = " incorrecta: Descripcion de compra invalida.";
          cases[9] = " incorrecta: Fecha invalida.";

          updateMessage("Linea " + (i + 1) + cases[validationResult]);
          
          updateProgress(i, limit);
          //concatenate this error code with the line, and send to the pipe.
          String stringToNextPipe = validationResult + "|" + currentWord;
          theOutQueueInstance.insertInto(stringToNextPipe);
          System.out.println(stringToNextPipe);

          i++;//go to the next element in the pipa
        }
        Thread.sleep(200);//wait
      }
    } catch (InterruptedException e) {
      System.out.println("Child interrupted.");
    }
    System.out.println("Exiting (consumer).");
    return null;
  }

  public int Validate(String line) {
    String[] tempTrace;
    String delimiter = "\\|";
    tempTrace = line.split(delimiter);
    int valid = 0;

    if (tempTrace.length != 9) {
      // number of pieces of information nos correct
      valid = 10;
    }

    for (int i = 0; i < tempTrace.length; i++) {
      if (tempTrace[i].equals("")) {
        //some piece of information is void
        valid = 11;
      }
    }
    if (!tempTrace[0].matches("CC|CE")) {//document type
      //type of document not matching
      valid = 1;
    }
    if (!tempTrace[1].matches("^\\d{4,10}$")) {//document number

      valid = 2;
    }
    if (!tempTrace[2].matches("^[a-zA-Z ]+$")) {//card owner
      //System.out.println("2");
      valid = 3;
    }
    if (!tempTrace[3].matches("CREDITO|DEBITO")) {//card type
      //System.out.println("3");
      valid = 4;
    }
    if (!tempTrace[4].matches("^\\d{0,16}$")) {//card number
      //System.out.println("4");
      valid = 5;
    }
    String[] cardVendors = {"AMEX", "VISA", "MC"};//list of franchises
    String finalStrFr = "";//list of frachises on a string
    for (String vend : cardVendors) {
      finalStrFr += vend + "|";
    }
    finalStrFr = finalStrFr.substring(0, finalStrFr.length() - 1);
    //System.out.println(finalStrFr);
    if (!tempTrace[5].matches(finalStrFr)) {//card franchise
      //System.out.println("5");
      valid = 6;
    }
    if (!tempTrace[6].matches("^\\d+$")) {//purchased ammount
      //System.out.println("6");
      valid = 7;
    }
    if (!tempTrace[7].matches("^[a-zA-Z ]+$")) {//purchase description
      //System.out.println("7");
      valid = 8;
    }
    if (!tempTrace[8].matches("^[012]\\d:[012345]\\d [0123]\\d/[01]\\d/\\d{4}$")) {//purchase date
      //System.out.println("8");
      valid = 9;
    }
    return valid;
  }
//  @Override
//  
//    throw new UnsupportedOperationException("Not supported yet.");
//  }
}